package com.crazyhat.crazyhat.config;

import java.lang.reflect.Array;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.crazyhat.crazyhat.interceptors.LoginInterceptors;

@Configuration
@ConfigurationProperties(prefix = "my-config.allow-path")
public class WebConfig implements WebMvcConfigurer{

    @Autowired
    private LoginInterceptors loginInterceptors;

    private List<String> allowPathList;

    /**
     * 跨域请求源列表
     */
    private List<String> allowOriginList;

    public List<String> getAllowOriginList() {
        return allowOriginList;
    }

    public void setAllowOriginList(List<String> allowOriginList) {
        this.allowOriginList = allowOriginList;
    }

    public List<String> getAllowPathList() {
        return allowPathList;
    }

    public void setAllowPathList(List<String> allowPathList) {
        this.allowPathList = allowPathList;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry
                .addInterceptor(loginInterceptors)
                .excludePathPatterns(this.allowPathList);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
            .addMapping("/**")
            .allowedOrigins(allowOriginList.toArray(new String[0])) //允许所有来源
            .allowedMethods("*") //允许所有访问方法
            .allowedHeaders("*") //允许所有请求头
            .allowCredentials(true) //允许携带cookie
            .maxAge(3600);//预检请求的有效期，单位为秒

        WebMvcConfigurer.super.addCorsMappings(registry);
    }
}
